﻿namespace SimpleX
{
    public static partial class ServicesExtension
    {
        public static IServiceCollection AddJwt(this IServiceCollection services)
        {
            var jwtSettings = App.Configuration.GetSection("JwtSettings").Get<JwtSettings>();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })

            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = jwtSettings.Issuer,
                    ValidAudience = jwtSettings.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Key))
                };

                options.Events = new JwtBearerEvents()
                {
                    //OnMessageReceived = m =>
                    //{
                    //    return Task.CompletedTask;
                    //},
                    OnChallenge = context =>
                    {
                        context.HandleResponse();
                        context.Response.Clear();
                        context.Response.ContentType = "application/json";
                        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;

                        var json = new UnifyResult<string>
                        {
                            Code = HttpStatusCode.Unauthorized,
                            Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
                            ElapsedMilliseconds = 0
                        }.ToJson();

                        context.Response.WriteAsync(json);
                        return Task.CompletedTask;
                    }
                };
            });

            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
            });

            return services;
        }
    }
}